package com.liujianlei.forum_system.controller;

import com.liujianlei.forum_system.common.AppResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author tongchen
 * @create 2023-06-05 18:05
 */
@Slf4j
@RestController
@RequestMapping("/common")
@Api(tags = "用户头像上传和下载的控制器")
public class CommonController {
    @Value("${forum.path}")
    private String path;
    @PostMapping("/upload")
    @ApiOperation("用户头像上传到服务器的方法")
    public AppResult upload(@ApiParam(value = "文件" ) @RequestParam MultipartFile file){
        log.info("文件信息为"+file);
        //获取文件原始名字
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成随机名字
        String prefix = UUID.randomUUID().toString();
        //将名字进行组合
        String fileName=prefix+suffix;
        //创建文件夹
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //将文件进行转存
        try {
            file.transferTo(new File(dir+fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return AppResult.success(fileName);
    }
    @GetMapping("/download")
    public AppResult download(String name , HttpServletResponse response){
        //创建输入流从文件中读取数据
        try {
            InputStream inputStream=new FileInputStream(new File(path+name));
            //创建输出流将文件传输到浏览器
            OutputStream outputStream=response.getOutputStream();
            //设置返回值类型
            response.setContentType("image/jpeg");
            int len=0;//判断是否读到了尽头
            byte[]bytes=new byte[1024];
            while((len=inputStream.read(bytes))!=-1){
                outputStream.write(bytes, 0, len);
                //刷新,保证文件全部被写入
                outputStream.flush();
            }
            //流资源的关闭
            outputStream.close();
            inputStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return AppResult.success("文件写回浏览器成功！");

    }


}
